//
//  COConversationListController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/7.
//

import UIKit

class COConversationListController: RCConversationListViewController {
    
    var cusService = "" // 客服
    var qaArr = [MarketQaModel]()
    
    var messageArray: NSMutableArray? {
        didSet {
            DispatchQueue.main.async {
                self.conversationListTableView.reloadData()
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        kLiveCalling.keySaveToNSDefaults(with: false)
        if(self.cusService.isEmptyStr == false){
            self.clearServiceMsg(serviceId: self.cusService)
        }
    }
    
    lazy var navView: UIView = {
        let nav = UIView()
        return nav
    }()
    
    lazy var msgTitle: UILabel = {
        let title = UILabel()
        title.text = "Message"
        title.font = UIFont.pingfangFont(ofSize: PTW(25), weight: .semibold)
        title.textColor = UIColor.white
        return title
    }()
    
    lazy var bgImg: UIImageView = {
        let nav = UIImageView()
        nav.image = KImaged("coco_main_bg")
        nav.contentMode = .scaleAspectFill
        nav.clipsToBounds = true
        return nav
    }()
    
    //MARK: --------- 客服按钮 ------------
    lazy var serviceBtn: UIButton = {
        let service = UIButton(type: .custom)
        service.setImage(KImaged("coco_msg_service"), for: .normal)
        service.addTarget(self, action: #selector(serviceAction), for: .touchUpInside)
        return service
    }()
    
    lazy var redView: UIView = {
        let res = UIView()
        res.layer.cornerRadius = PTW(4)
        res.layer.masksToBounds = true
        res.backgroundColor = UIColor.colorWithHex("#03FF74")
        res.isHidden = true
        return res
    }()
    
    override func willReloadTableData(_ dataSource: NSMutableArray!) -> NSMutableArray! {
        let messageArray = NSMutableArray()
        if(self.cusService.isEmptyStr == true){
            return messageArray
        }
        self.clearServiceMsg(serviceId: self.cusService)
        for model in dataSource {
            let result = model as! RCConversationModel
            result.conversationModelType = .CONVERSATION_MODEL_TYPE_CUSTOMIZATION
            if result.conversationType == .ConversationType_SYSTEM {
                messageArray.insert(result, at: 0)
                continue
            }
            if(result.targetId == self.cusService){
                continue
            }
            messageArray.add(result)
        }
        var id = String()
        for model in messageArray {
            let result = model as! RCConversationModel
            if let index =  result.targetId.firstIndex(of: Character("_")) {
                let substring = String(result.targetId[result.targetId.index(after: index)...])
                id.append(substring)
                id.append(",")
            } else {
                continue
            }
        }
        if (id.count > 0 && id.suffix(1) == ","){
            id = String(id.dropLast())
        }
        self.getUserInfoData(ids: id)
        return messageArray
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.getMarketingQaAcrion()
        xl_prefersNavigationBarHidden = true
        xl_interactivePopMaxAllowedInitialDistanceToLeftEdge = PTW(200)
        
        self.view.addSubview(self.bgImg)
        self.bgImg.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.view.addSubview(self.navView)
        self.navView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(KStatusAndNavBarHeight)
        }
        self.navView.addSubview(self.msgTitle)
        self.msgTitle.snp.makeConstraints { make in
            make.centerX.equalTo(self.navView)
            make.bottom.equalTo(self.navView)
            make.height.equalTo(44)
        }
        self.view.addSubview(self.serviceBtn)
        self.view.addSubview(self.redView)
        self.serviceBtn.snp.makeConstraints { make in
            make.size.equalTo(PTW(44))
            make.centerY.equalTo(self.msgTitle)
            make.right.equalToSuperview().offset(-PTW(15))
        }
        self.redView.snp.makeConstraints { make in
            make.size.equalTo(PTW(8))
            make.top.right.equalTo(self.serviceBtn)
        }
        
        self.view.sendSubviewToBack(self.bgImg)
        
        self.setDisplayConversationTypes([RCConversationType.ConversationType_PRIVATE.rawValue, RCConversationType.ConversationType_SYSTEM.rawValue])
        self.conversationListTableView.separatorStyle = .none
        self.conversationListTableView.tableFooterView = UIView()
        self.conversationListTableView.backgroundColor = .clear
        self.conversationListTableView.frame = CGRectMake(0, KStatusAndNavBarHeight, SCREENWIDTH, SCREENHEIGHT - KStatusAndNavBarHeight - KTabBarAndSafeHeight - PTW(10))
        self.conversationListTableView.contentInsetAdjustmentBehavior = .never
        // 获取礼物列表
        KAppDelegate.getGiftSearchList()
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messageArray?.count ?? 0
    }
     
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 135
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:COCOnversationViewCell = COCOnversationViewCell().cellWithTableView(tableView)
        cell.selectionStyle = .none
        if self.messageArray?.count ?? 0 > 0 {
            let conversation = self.messageArray![indexPath.row] as! RCConversationModel
            cell.setDataModel(conversation)
        }
        return cell
    }
    
    // 左滑删除
    override func rcConversationListTableView(_ tableView: UITableView!, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath!) {
        let conversation = self.messageArray![indexPath.row] as! RCConversationModel
        if conversation.conversationType == .ConversationType_SYSTEM {
            return
        }
        RCIMClient.shared().remove(conversation.conversationType, targetId: conversation.targetId)
        self.messageArray?.remove(conversation)
        self.conversationListTableView.reloadData()
    }
    
    // 选中cell
    override func onSelectedTableRow(_ conversationModelType: RCConversationModelType, conversationModel model: RCConversationModel!, at indexPath: IndexPath!) {
        let model = self.messageArray?[indexPath.item] as! RCConversationModel
        let chat =  COChatViewController()
        chat.conversationType = model.conversationType
        chat.targetId = model.targetId
        navigationController?.pushViewController(chat, animated: true)
        RCIMClient.shared().clearMessagesUnreadStatus(model.conversationType, targetId: model.targetId)
        COChatMsgManager.shared.setBadgeValue()
    }
    
    func clearServiceMsg(serviceId:String){
        DispatchQueue.main.safeAsync {
            let count = RCIMClient.shared().getUnreadCount(.ConversationType_PRIVATE, targetId: self.cusService)
            self.redView.isHidden = count > 0 ? false:true
        }
    }
    
    //MARK: --------- 客服点击 ------------
    @objc func serviceAction(){
        if(self.cusService.isEmptyStr == true){
            self.view.makeToast("Customer service is busy now, please try again later!")
            return
        }
        let chat = COServiceViewController()
        chat.targetId = self.cusService
        chat.qaArr = self.qaArr
        chat.conversationType = .ConversationType_PRIVATE
        chat.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(chat, animated: true)
        RCIMClient.shared().clearMessagesUnreadStatus(.ConversationType_PRIVATE, targetId: chat.targetId)
        self.redView.isHidden = true
    }
    
    func getUserInfoData(ids:String){
        var params = [String:Any]()
        params["ids"] =  ids
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        let target = feed == true ? COBaseApi.getListUserInfo(param: params):COBaseApi.getListStreamerInfo(param: params)
        COHttpManager.request(target: target, modelType: COChatUsersModel.self) { code, object, success in
            DispatchQueue.global(qos: .default).async { [self] in
                let chatList = object?.users
                for model in self.conversationListDataSource {
                    let result = model as! RCConversationModel
                    if chatList?.count ?? 0 > 0{
                        for curUser in chatList! {
                            if (result.targetId.contains(curUser.id)){
                                result.extend = curUser.status
                                break
                            }
                        }
                    }
                }
                self.messageArray = self.conversationListDataSource
            }
        } failureBlock: { code, msg in
        }
    }
    
    //MARK: ---------  Q&A list ------------
    func getMarketingQaAcrion(){
        var params = [String:Any]()
        params["pageNum"]  = 1
        params["pageSize"] = 100
        COHttpManager.request(target: COBaseApi.marketQa(param: params), modelType: COMarketQaDatasModel.self) {[weak self] code, object, success in
            self?.qaArr.removeAll()
            let tempArr = object?.pageData
            for i in 0..<(tempArr?.count ?? 0) {
                let qamodel = tempArr![i] as MarketQaModel
                if (qamodel.id == 1){
                    self?.cusService = "streamer_\(qamodel.answer)"
                    kCustomerService.keySaveToNSDefaults(with: self?.cusService)
                    self?.clearServiceMsg(serviceId: self!.cusService)
                    DispatchQueue.main.safeAsync {
                        self?.refreshConversationTableViewIfNeeded()
                    }
                }else{
                    self?.qaArr.append(qamodel)
                }
            }
        } failureBlock: { code, msg in
            print("\(msg ?? "")")
        }
    }
}
